package com.tianshi.agriculture.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.tianshi.agriculture.R;
import com.tianshi.agriculture.databinding.ReadDataLayoutBinding;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.BleController;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.OnReceiverCallback;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.OnWriteCallback;
import com.tianshi.agriculture.utils.ModbusUtils.ByteUtil;
import com.tianshi.agriculture.utils.ModbusUtils.ModbusError;
import com.tianshi.agriculture.utils.ModbusUtils.ModbusRTUHelper;

import java.util.Arrays;

public class ReadDataFragment extends Fragment {

    private ReadDataLayoutBinding binding;
    public static final String REQUESTKEY_SENDANDRECIVEACTIVITY = "ReadDataFragment";
    private int readNumberOfPoints = 40;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        ReadDataModel readDataModel =
                new ViewModelProvider(this).get(ReadDataModel.class);

        binding = ReadDataLayoutBinding.inflate(inflater, container, false);
        View root = binding.getRoot();


        binding.readDataButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] bytes1 = null;
                try {
                    bytes1 = ModbusRTUHelper.readInputRegisters(1, 0, readNumberOfPoints);
                    System.out.println("发送:>>>" + BleController.getInstance().bytesToHexString(bytes1));

                    BleController.getInstance().writeBuffer(bytes1, new OnWriteCallback() {
                        @Override
                        public void onSuccess() {
                            clearResult();
                        }

                        @Override
                        public void onFailed(int state) {
                            Toast.makeText(getActivity(), "发送失败！", Toast.LENGTH_SHORT).show();
                        }
                    });

                } catch (ModbusError e) {
                    throw new RuntimeException(e);
                }

            }
        });

        return root;
    }



    public void exitFragment() {
        BleController.getInstance().unregistReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY);

    }

    public void enterFragment() {
        BleController.getInstance().unregistReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY);

        // TODO 接收数据的监听
        BleController.getInstance().registReciveListener(REQUESTKEY_SENDANDRECIVEACTIVITY, new OnReceiverCallback() {
            @Override
            public void onRecive(byte[] value) {
                if(binding == null) {
                    return;
                }

                if(value.length != readNumberOfPoints * 2 + 5) {
                    return;
                }

                value = Arrays.copyOfRange(value,3,value.length);
                // 这里为了演示方便，把 byte数组转字符串显示
                short kd = ByteUtil.bytesToInt16(value[0*2],value[0*2+1]);  //开度
                short jsylDL = ByteUtil.bytesToInt16(value[1*2],value[1*2+1]);  //进水压力（电流）
                short hsylDL = ByteUtil.bytesToInt16(value[2*2],value[2*2+1]);  //回水压力（电流）
                short jsyl = ByteUtil.bytesToInt16(value[3*2],value[3*2+1]); //进水压力1
                short hsyl = ByteUtil.bytesToInt16(value[4*2],value[4*2+1]); //回水压力1
                short jswdDZ = ByteUtil.bytesToInt16(value[5*2],value[5*2+1]); //进水温度(电阻)
                short hswdDZ = ByteUtil.bytesToInt16(value[6*2],value[6*2+1]); //回水温度(电阻)
                short jswd = ByteUtil.bytesToInt16(value[7*2],value[7*2+1]); //进水温度
                short hswd = ByteUtil.bytesToInt16(value[8*2],value[8*2+1]); //回水温度
                short reserve1 = ByteUtil.bytesToInt16(value[9*2],value[9*2+1]); //保留
                short reserve2 = ByteUtil.bytesToInt16(value[10*2],value[10*2+1]); //保留
                short reserve3 = ByteUtil.bytesToInt16(value[11*2],value[11*2+1]); //保留
                short reserve4 = ByteUtil.bytesToInt16(value[12*2],value[12*2+1]); //保留
                int errorNo = ByteUtil.bytesToUint16(value[13*2],value[13*2+1]); //错误号
                int alarmState = ByteUtil.bytesToUint16(value[14*2],value[14*2+1]); //报警状态
                short reserve5 = ByteUtil.bytesToInt16(value[15*2],value[15*2+1]); //保留
                short reserve6 = ByteUtil.bytesToInt16(value[16*2],value[16*2+1]); //保留



                long equiNo = ByteUtil.bytesToUint32(value[17*2],value[17*2+1],value[17*2+2],value[17*2+3]); //Equi序列号
//                long equiNo = ByteUtil.bytesToUint32(ByteUtil.fromInt32Reverse(-1886846095)); //Equi序列号

                int softVersion = ByteUtil.bytesToUint16(value[19*2],value[19*2+1]); //软件版本
                short zdqs = ByteUtil.bytesToInt16(value[31*2],value[31*2+1]);  //转圈数
                int dqjdcgq = ByteUtil.bytesToUint16(value[33*2],value[33*2+1]); //单圈角度传感器(原始ADC)


                double kdValue = kd * 0.1;
                double jsylDLValue = jsylDL * 0.001;
                double hsylDLValue = hsylDL * 0.001;
                double jsylValue = jsyl * 0.001;
                double hsylValue = hsyl * 0.001;
                double jswdDZValue = jswdDZ * 0.001;
                double hswdDZValue = hswdDZ * 0.001;
                double jswdValue = jswd * 0.01;
                double hswdValue = hswd * 0.01;


                binding.valueEqui.setText(equiNo+"");
                binding.valueSoftVersion.setText(softVersion+"");
                binding.valueErrorNo.setText(errorNo+"");
                binding.valueKD.setText(kdValue + " %");
                binding.valueJSYL.setText(jsylValue+" MPa");
                binding.valueHSYL.setText(hsylValue+" MPa");
                binding.valueJSWD.setText(hswdValue+ " ℃");
                binding.valueHSWD.setText(jswdValue + " ℃");
                binding.valueZDQS.setText(zdqs+"");
                binding.valueDQJDCGQ.setText(dqjdcgq+"");

//                Toast.makeText(getActivity(), "数据读取成功！", Toast.LENGTH_SHORT).show();
                //打印上面解析出来的变量值
                System.out.println("kd:" + kdValue);
                System.out.println("jsylDL:" + jsylDLValue);
                System.out.println("hsylDL:" + hsylDLValue);
                System.out.println("jsyl:" + jsylValue);
                System.out.println("hsyl:" + hsylValue);
                System.out.println("jswdDZ:" + jswdDZValue);
                System.out.println("hswdDZ:" + hswdDZValue);
                System.out.println("jswd:" + jswdValue);
                System.out.println("hswd:" + hswdValue +"");

                System.out.println("reserve1:" + reserve1);
                System.out.println("reserve2:" + reserve2);
                System.out.println("reserve3:" + reserve3);
                System.out.println("reserve4:" + reserve4);

                System.out.println("errorNo:" + errorNo);
                System.out.println("alarmState:" + alarmState);
                System.out.println("reserve5:" + reserve5);
                System.out.println("reserve6:" + reserve6);

                System.out.println("equiNo:" + equiNo);
                System.out.println("softVersion:" + softVersion);

                System.out.println("zdqs:" + zdqs);
                System.out.println("dqjdcgq:" + dqjdcgq);
                System.out.println("-----------");
            }
        });
    }

    public void clearResult() {
        binding.valueEqui.setText("");
        binding.valueSoftVersion.setText("");
        binding.valueErrorNo.setText("");
        binding.valueKD.setText("");
        binding.valueJSYL.setText("");
        binding.valueHSYL.setText("");
        binding.valueJSWD.setText("");
        binding.valueHSWD.setText("");
        binding.valueZDQS.setText("");
        binding.valueDQJDCGQ.setText("");

    }

    @Override
    public void onStart() {
        super.onStart();

        enterFragment();

        //进页面先读取一次全部参数
        binding.readDataButton.performClick();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        exitFragment();
        binding = null;
    }
}